package com.sunmouse.toolkit.fragment.socket;


import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;

import com.sunmouse.toollib.receiver.OnReceiveListener;
import com.sunmouse.toollib.utils.StringUtils;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.adapter.ExceptionAdapter;
import com.sunmouse.toolkit.bean.ExceptionBean;
import com.sunmouse.toolkit.receiver.ExceptionReceiver;
import com.sunmouse.toolkit.constant.Config;
import com.sunmouse.toolkit.constant.Value;
import com.sunmouse.toolkit.fragment.BaseFragment;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class SocketFragment extends BaseFragment implements CompoundButton.OnCheckedChangeListener{


    @BindView(R.id.exception_lv)
    RecyclerView exceptionLv;
    @BindView(R.id.server_sw)
    Switch serverSw;
    @BindView(R.id.client_sw)
    Switch clientSw;
    Unbinder unbinder;

    private ExceptionAdapter mAdapter;
    private ArrayList<ExceptionBean> exceptions;
    private ExceptionBean bean;
    private ExceptionReceiver mReceiver;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_socket, container, false);
        unbinder = ButterKnife.bind(this, v);
        return v;
    }

    @Override
    public void init() {
        this.exceptionLv.setPadding(0, findStatusBarHeight(), 0, 0);
        this.serverSw.setText("通知");
        this.serverSw.setChecked(true);
        this.clientSw.setOnCheckedChangeListener(this);
        this.serverSw.setOnCheckedChangeListener(this);
        int status = mPersistentUtils.readInt(Config.Key.STATUS);
        if (status == Value.CONNECTED) this.clientSw.setChecked(true);
        status = mPersistentUtils.readInt(Config.Key.NOTIFICATION_STATUS);
        this.serverSw.setChecked(status != Value.Control.CLOSE_NOTIFICATION);

        exceptions = new ArrayList<>();
        mAdapter = new ExceptionAdapter(exceptions, getActivity());
        this.exceptionLv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        this.exceptionLv.setAdapter(mAdapter);

        this.mBundle=getArguments();
        String msg = mBundle.getString(Config.Key.EXCEPTION);
        loadHistory();

        mReceiver = new ExceptionReceiver();
        getActivity().registerReceiver(mReceiver, new IntentFilter(Value.Action.EXCEPTION_RECEIVER));
        mReceiver.setOnReceiveListener(new ExceptionHandle());
    }

    /**
     * find status bar height
     *
     * @return
     */
    private int findStatusBarHeight() {
        int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        int result = getResources().getDimensionPixelSize(resId);
        return result <= 0 ? 0 : result;
    }

    /**
     * read history exception info
     */
    private void loadHistory() {
        ArrayList<String> ef = mPersistentUtils.readList(Config.Key.EXCEPTION);
        if (ef==null)return;
        for (int i = 0; i < ef.size(); i++) {
            bean = new ExceptionBean();
            bean.setStationName(generateRandomName());
            bean.setLevel(generateRandomLevel());
            bean.setDesc(ef.get(i));

            exceptions.add(bean);
        }
        mAdapter.notifyDataSetChanged();
        this.exceptionLv.smoothScrollToPosition(exceptions.size() - 1);
    }

    private String generateRandomLevel() {
        int rand = (int) ((10 * Math.random() + 3) / 3);
        return rand + "级";
    }

    /**
     * generate random station name
     *
     * @return
     */
    private String generateRandomName() {
        int rand = (int) ((10 * Math.random() + 3) / 3);
        return rand + "号电站";
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView == clientSw) {
            if (isChecked)
                sendCommand(Value.Control.CONNECT);
            else
                sendCommand(Value.Control.DISCONNECT);
        } else if (buttonView == serverSw) {
            sendCommand(isChecked ? Value.Control.OPEN_NOTIFICATION : Value.Control.CLOSE_NOTIFICATION);
        }
    }

    private void sendCommand(int control) {
        mIntent = new Intent(Value.Action.EXCEPTION);
        mIntent.putExtra(Config.Key.CONTROL, control);
        getActivity().sendBroadcast(mIntent);
    }




    /**
     * handle received exception
     */
    private class ExceptionHandle implements OnReceiveListener {
        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getStringExtra(Config.Key.EXCEPTION);
//            LogUtils.v("---SocketActivity----" + msg);
            if (!StringUtils.isEmpty(msg)) {
                bean = new ExceptionBean();
                bean.setStationName(generateRandomName());
                bean.setLevel(generateRandomLevel());
                bean.setDesc(msg);
                exceptions.add(bean);
//                LogUtils.d("------------------count-----------" + mAdapter.getCount());
                exceptionLv.getAdapter().notifyDataSetChanged();
//                exceptionLv.scrollToPosition(exceptions.size() - 1);
                exceptionLv.smoothScrollToPosition(exceptions.size() - 1);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        getActivity().unregisterReceiver(mReceiver);


    }
}
